package com.xbongbong.saas.analytical.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.ConfigConstant;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataValidateDataHelp;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.help.SerialNoHelp;
import com.xbongbong.paas.help.team.TeamUserHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.pojo.AddMuchFieldPojo;
import com.xbongbong.paas.pojo.dto.AddBatchDTO;
import com.xbongbong.paas.pojo.dto.AggSumDTO;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateGetDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.AggSumVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.domain.entity.FormConfigEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PayErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PaymentErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PurchaseErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ImportErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.saas.analytical.SaasValidateAnalyticalService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.LinkAddOperationFlagEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.help.SaasDataInitHelp;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.model.FormConfigModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.service.toolbox.help.FundMoneyHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.util.ValidateUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author 吴峰
 * @date 2021/07/15 17:15
 */
@Service("payPlanAnalyticalServiceImpl")
public class PayPlanValidateAnalyticalServiceImpl implements SaasValidateAnalyticalService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(PayPlanValidateAnalyticalServiceImpl.class);
    
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private FundMoneyHelp fundMoneyHelp;
    @Resource
    private FormConfigModel formConfigModel;
    @Resource
    private FormDataValidateDataHelp formDataValidateDataHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private SerialNoHelp serialNoHelp;
    @Resource
    private TeamUserHelp teamUserHelp;

    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.PAY_PLAN.getCode());
    }

    @Override
    public void analyticalData(ValidateDataDTO validateDataDTO) throws XbbException {
        beforeSave(validateDataDTO);
        teamUserHelp.beforeVerifyUserTeam(validateDataDTO);
    }
    
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        try {
            JSONObject data = validateDataDTO.getData();
            PayPlanEntityExt payPlanEntityExt = null ;
            List<Long> idIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if ( validateDataDTO.getDataId() != null ) {
                payPlanEntityExt = payPlanModel.getByKey(validateDataDTO.getDataId(),validateDataDTO.getCorpid());
                idIn.add(validateDataDTO.getDataId());
            }
            SaveFormatHelp.formatLinkBusiness4SaveByArray(data, PayPlanEnum.LINK_SUPPLIER.getAttr(), PayPlanEnum.LINK_SUPPLIER_LINK_TEXT.getAttr(), PayPlanEnum.LINK_SUPPLIER.getFieldType());
            SaveFormatHelp.formatLinkBusiness4SaveByArray(data, PayPlanEnum.LINK_PURCHASE.getAttr(), PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr(), PayPlanEnum.LINK_PURCHASE.getFieldType());
            JSONObject oldData = new JSONObject();
            if (payPlanEntityExt != null) {
                oldData = payPlanEntityExt.getData();
            }
            Long purchaseId = FastJsonHelper.getLongOrDefaultFromFormData(data, PayPlanEnum.LINK_PURCHASE.getAttr(), 0L);
            PurchaseEntityExt purchaseEntityExt = purchaseModel.getByKey(purchaseId, validateDataDTO.getCorpid());
            if (Objects.isNull(purchaseEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }

            FormDataUpdateGetDTO formDataUpdateGetDTO = new FormDataUpdateGetDTO();
            BeanUtil.copyProperties(validateDataDTO,formDataUpdateGetDTO);
            Double payPlanAmount = beforeSaveGetTotalAmount(validateDataDTO.getCorpid(), purchaseId, idIn, true, formDataUpdateGetDTO);
            Double amount = getDoubleOrDefaultFromFormData(data, PayPlanEnum.AMOUNT.getAttr(), 0D);
            Double purchaseAmount = getDoubleOrDefaultFromFormData(purchaseEntityExt.getData(), PurchaseEnum.TOTAL_MONEY.getAttr(), 0D);
            //允许误差小于等于ConfigConstant.amountAccuracy
            if (Arith.sub(Arith.add(payPlanAmount, amount), purchaseAmount) > ConfigConstant.amountAccuracy) {
                throw new XbbException(PayErrorCodeEnum.API_ERROR_226009);
            }
            if ( validateDataDTO.getDataId() == null && Objects.equals(validateDataDTO.getIsImport(), 1) ){
                if (!Objects.equals(data.getString(PayPlanEnum.STATUS.getAttr()), PayPlanStatusEnum.UN_RECEIVABLES.getCode())) {
                    throw new XbbException(ImportErrorCodeEnum.API_ERROR_235027);
                }
                if ( amount<=0 ){
                    throw new XbbException(ImportErrorCodeEnum.API_ERROR_235030);
                }
                data.put(PayPlanEnum.UN_AMOUNT.getAttr(), amount);
                data.put(PayPlanEnum.REAL_AMOUNT.getAttr(), 0);
            }else{
                if (Objects.equals(oldData.getString(PayPlanEnum.STATUS.getAttr()), PayPlanStatusEnum.UN_RECEIVABLES.getCode())) {
                    data.put(PayPlanEnum.UN_AMOUNT.getAttr(), amount);
                    data.put(PayPlanEnum.REAL_AMOUNT.getAttr(), 0);
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("payPlanAnalyticalServiceImpl.beforeSave error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
    public AddBatchDTO beforeSaveBatch(FormDataAddDTO formDataSaveDTO, boolean fromApproval) throws XbbException {
        Map<String, Object> params = BeanUtil.convertBean2Map(formDataSaveDTO, true);
        List<PaasFormExplainEntity> explainList = paasFormExplainModel.list(params);
        if (Objects.isNull(explainList) || explainList.isEmpty()) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainList.get(0).getExplains(), null);
        JSONObject data = formDataSaveDTO.getDataList();
        JSONArray jsonArray = data.getJSONArray(PayPlanEnum.ADD_PAYPLAN.getAttr());
        for (Object item : jsonArray) {
            JSONObject jsonObject = (JSONObject) item;
            SaveFormatHelp.dealLabelData(jsonObject.getJSONObject("data"), explainMap);
        }
        data.put(PayPlanEnum.ADD_PAYPLAN.getAttr(), jsonArray);
        SaveFormatHelp.formatLinkBusiness4SaveByArray(data, PayPlanEnum.LINK_SUPPLIER.getAttr(), PayPlanEnum.LINK_SUPPLIER_LINK_TEXT.getAttr(), PayPlanEnum.LINK_SUPPLIER.getFieldType());
        SaveFormatHelp.formatLinkBusiness4SaveByArray(data, PayPlanEnum.LINK_PURCHASE.getAttr(), PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr(), PayPlanEnum.LINK_PURCHASE.getFieldType());
        JSONArray paymentArray = data.getJSONArray(PayPlanEnum.ADD_PAYPLAN.getAttr());
        Double purchaseAmount;
        Long purchaseId = null;
        Boolean isNew = false;
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = formDataSaveDTO.getSaasNeedRedundantAttrPoJo();
        // 来自于采购合同新建编辑
        if (Objects.nonNull(saasNeedRedundantAttrPoJo) && Objects.equals(saasNeedRedundantAttrPoJo.getParentBusinessType(), XbbRefTypeEnum.PURCHASE.getCode())) {
            purchaseAmount = formDataSaveDTO.getSaasNeedRedundantAttrPoJo().getParentAmount();
            isNew = true;
        } else {
            PaasFormDataEntityExt purchaseEntityExt = purchaseModel.getByKey(data.getLong(PayPlanEnum.LINK_PURCHASE.getAttr()),formDataSaveDTO.getCorpid());
            if (Objects.isNull(purchaseEntityExt)) {
                throw new XbbException(PurchaseErrorCodeEnum.API_ERROR_225006);
            }
            purchaseAmount =  purchaseEntityExt.getData().getDouble(PurchaseEnum.TOTAL_MONEY.getAttr());
            purchaseId = purchaseEntityExt.getId();
            isNew = false;
        }
        Double payPlanAmount = 0D;
        List<AddMuchFieldPojo> addBatchList = new ArrayList<>();
        List<AddMuchFieldPojo> delBatchList = new ArrayList<>();
        List<AddMuchFieldPojo> updateBatchList = new ArrayList<>();
        // 没有变心的付款计划，不需要再入库
        List<Object> otherList = new ArrayList<>();
        List<ValidateDataDTO> validateDataDTOList = new ArrayList<>();
        List<Long> idIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        FieldAttrEntity serialNoEntity = explainMap.get(PurchaseEnum.SHEET_NO.getAttr());
        //下面是移除审批中已经删除的付款计划
        fundHelp.handProcessShouldRemoveValue(formDataSaveDTO.getCorpid(), XbbRefTypeEnum.PURCHASE, XbbRefTypeEnum.PAY_PLAN, paymentArray);
        for (Object obj : paymentArray){
            AddMuchFieldPojo addMuchFieldPojo = new AddMuchFieldPojo();
            ValidateDataDTO validateDataDTO = new ValidateDataDTO();
            JSONObject json = (JSONObject) obj;
            Long dataId = json.getLong(StringConstant.DATA_ID);
            addMuchFieldPojo.setId(dataId);
            String serialNo = json.getString(FieldTypeEnum.SERIALNO.getAlias());
            if (Objects.nonNull(serialNoEntity) && Objects.equals(serialNoEntity.getStrictController(), BasicConstant.ONE) && StringUtil.isEmpty(serialNo)) {
                serialNo = serialNoHelp.getSerialNo(serialNo, formDataSaveDTO.getCorpid(), formDataSaveDTO.getFormId(),  serialNoEntity);
                formDataSaveDTO.setSerialNo(serialNo);
                json.getJSONObject("data").put(FieldTypeEnum.SERIALNO.getAlias(), serialNo);
            }
            if ( StringUtil.isNotEmpty(serialNo) && serialNo.length()>BasicConstant.SERIAL_LENGTH_NUMBER) {
                throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208061,String.format(PaymentErrorCodeEnum.API_ERROR_208061.getMsg(),BasicConstant.SERIAL_LENGTH_NUMBER));
            }
            addMuchFieldPojo.setSerialNo(serialNo);
            JSONObject paymentData = json.getJSONObject("data");
            for (Map.Entry<String,Object> entry : SaasDataInitHelp.initPayPlan().entrySet()){
                SaasDataInitHelp.antDataSet(paymentData,entry.getKey(),entry.getValue());
            }
            JSONObject statusJSON = FastJsonHelper.getJsonObjectOrDefaultFromFormData(paymentData, PayPlanEnum.STATUS.getAttr(),new JSONObject());
            String status = statusJSON.getString("value");
           /* if ( !Objects.equals(status, PayPlanStatusEnum.UN_RECEIVABLES.getCode()) && Objects.isNull(dataId) && Objects.isNull(formDataSaveDTO.getIsOldProgressData())){
                throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208055, PaymentErrorCodeEnum.API_ERROR_208055.getMsg());
            }*/
            Integer operationFlag = json.getInteger(StringConstant.OPERATION_FLAG);
            if ( Objects.isNull(dataId) ) {
                operationFlag = null;
            }
            if ( !Objects.equals(operationFlag,LinkAddOperationFlagEnum.DEL.getCode()) ) {
                ValidateUtil.validatePayment(paymentData,PayPlanEnum.AMOUNT.getAttr(),explainMap);
            }
            paymentData.put(PayPlanEnum.LINK_SUPPLIER.getAttr(),data.get(PayPlanEnum.LINK_SUPPLIER.getAttr()));
            paymentData.put(PayPlanEnum.LINK_SUPPLIER_LINK_TEXT.getAttr(),data.get(PayPlanEnum.LINK_SUPPLIER_LINK_TEXT.getAttr()));
            paymentData.put(PayPlanEnum.LINK_PURCHASE.getAttr(),data.get(PayPlanEnum.LINK_PURCHASE.getAttr()));
            paymentData.put(PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr(),data.get(PayPlanEnum.LINK_PURCHASE_LINK_TEXT.getAttr()));
            addMuchFieldPojo.setData(paymentData);
            BeanUtil.copyProperties(formDataSaveDTO,validateDataDTO);
            validateDataDTO.setBusinessType(XbbRefTypeEnum.PAY_PLAN.getCode());
            validateDataDTO.setSerialNo(serialNo);
            validateDataDTO.setData(addMuchFieldPojo.getData());
            validateDataDTO.setDataId(dataId);
            validateDataDTO.setFromApproval(fromApproval);
            if (Objects.equals(operationFlag,LinkAddOperationFlagEnum.DEL.getCode())){
                delBatchList.add(addMuchFieldPojo);
                idIn.add(addMuchFieldPojo.getId());
            } else {
                if (Objects.equals(operationFlag,LinkAddOperationFlagEnum.EDIT.getCode())){
                    updateBatchList.add(addMuchFieldPojo);
                    validateDataDTOList.add(validateDataDTO);
                    idIn.add(addMuchFieldPojo.getId());
                    validateTeam(paymentData, validateDataDTO, addMuchFieldPojo);
                } else if (Objects.isNull(dataId)){
                    addBatchList.add(addMuchFieldPojo);
                    validateDataDTOList.add(validateDataDTO);
                    validateTeam(paymentData, validateDataDTO, addMuchFieldPojo);
                } else {
                    otherList.add(obj);
                    idIn.add(addMuchFieldPojo.getId());
                }
                payPlanAmount = Arith.add(payPlanAmount, getDoubleOrDefaultFromFormData(paymentData, PayPlanEnum.AMOUNT.getAttr(), 0D));
            }
            //校验团队负责人之后需要重新变成原来入参的样子，因为这边回款单校验也会走一次这个ProSaveHelp.analyticalData方法
            JSONArray originalOwnerArray = paymentData.getJSONArray(FieldTypeEnum.OWNERID.getAlias());
            JSONArray originalCouserArray = paymentData.getJSONArray(FieldTypeEnum.COUSERID.getAlias());
            validateDataDTO.setExplainMap(explainMap);
            ProSaveHelp.analyticalData(validateDataDTO);
            formDataValidateDataHelp.validateData(validateDataDTO);
            addMuchFieldPojo.setDepartmentId(validateDataDTO.getDepartmentId());
            paymentData.put(FieldTypeEnum.DEPARTMENTID.getAlias(), validateDataDTO.getDepartmentId());
            paymentData.put(FieldTypeEnum.OWNERID.getAlias(), originalOwnerArray);
            paymentData.put(FieldTypeEnum.COUSERID.getAlias(), originalCouserArray);
        }

        if (!isNew && purchaseId != null && purchaseId != 0L) {
            FormDataUpdateGetDTO formDataUpdateGetDTO = new FormDataUpdateGetDTO();
            BeanUtil.copyProperties(formDataSaveDTO, formDataUpdateGetDTO);
            payPlanAmount = Arith.add(payPlanAmount,beforeSaveGetTotalAmount(formDataSaveDTO.getCorpid(), purchaseId, idIn,formDataSaveDTO.getIsTotalPaymentSheetAmount(),formDataUpdateGetDTO));
        }
        if ( payPlanAmount < BasicConstant.ZERO_DOUBLE ) {
            throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208034, PaymentErrorCodeEnum.API_ERROR_208034.getMsg(), PayPlanEnum.AMOUNT.getAttrName());
        }
        //允许误差小于等于ConfigConstant.amountAccuracy
        if (Arith.sub(payPlanAmount, purchaseAmount) > ConfigConstant.amountAccuracy) {
            throw new XbbException(PayErrorCodeEnum.API_ERROR_226009);
        }
        // 只有在采购合同新建时，需要根据采购合同开关设置去做金额相等校验
        FormConfigEntity formConfigEntity = formConfigModel.getEntityByBusinessType(formDataSaveDTO.getCorpid(), XbbRefTypeEnum.PURCHASE.getCode(), FormConfigEnum.PURCHASE_AMOUNT_EQUAL_PAYMENT_PLAN.getConfig());
        boolean ispurchaseAmountEqualPaymentPlan = Objects.equals(FormConfigEnum.PURCHASE_AMOUNT_EQUAL_PAYMENT_PLAN.getConfigValue(), StringConstant.POSITIVE_NUMBER);
        if (Objects.nonNull(formConfigEntity)) {
            if (Objects.equals(formConfigEntity.getConfigValue(), StringConstant.POSITIVE_NUMBER)) {
                ispurchaseAmountEqualPaymentPlan = true;
            } else {
                ispurchaseAmountEqualPaymentPlan = false;
            }
        }
        //
        if (ispurchaseAmountEqualPaymentPlan && (!addBatchList.isEmpty() || !updateBatchList.isEmpty() || !otherList.isEmpty())) {
            if (!Objects.equals(payPlanAmount, purchaseAmount) && formDataSaveDTO.getIsTotalPaymentSheetAmount()) {
                throw new XbbException(PayErrorCodeEnum.API_ERROR_226011);
            }
        }
        AddBatchDTO addBatchDTO = new AddBatchDTO();
        BeanUtil.copyProperties(formDataSaveDTO,addBatchDTO);
        addBatchDTO.setAddBatchList(addBatchList);
        FieldAttrEntity serialField = explainMap.getOrDefault(PayPlanEnum.PAY_PLAN_NO.getAttr(), new FieldAttrEntity());
        if (Objects.equals(serialField.getNoRepeat(), 1)) {
            Set<String> addSerialNoSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            addBatchList.forEach(addBatch-> addSerialNoSet.add(addBatch.getSerialNo()));
            if (!Objects.equals(addSerialNoSet.size(), addBatchList.size())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.NO_REPEAT, serialField.getAttrName());
            }
        }
        Integer total = addBatchList.size() + updateBatchList.size() - delBatchList.size();
        if ( total > StringConstant.MAX_PAY_PLAN_COUNT ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028, ErrorMessageConstant.OVER_STEP_MAX_PAY_PLAN_COUNT, StringConstant.MAX_PAY_PLAN_COUNT);
        }
        addBatchDTO.setAmount(payPlanAmount);
        addBatchDTO.setUpdateBatchList(updateBatchList);
        addBatchDTO.setDelBatchList(delBatchList);
        addBatchDTO.setValidateDataDTOList(validateDataDTOList);
        return addBatchDTO;
    }

    /**
     * 校验团队并且往参数中封装团队信息
     *
     * @param json
     * @param validateDataDTO
     * @param addMuchFieldPojo
     */
    private void validateTeam(JSONObject json, ValidateDataDTO validateDataDTO, AddMuchFieldPojo addMuchFieldPojo) throws XbbException {
        JSONArray teamMainPojoArray = json.getJSONArray(FieldTypeEnum.OWNERID.getAlias());
        JSONArray teamCoPojoArray = json.getJSONArray(FieldTypeEnum.COUSERID.getAlias());
        validateDataDTO.setOwnerIds(null);
        validateDataDTO.setCoUserId(null);
        if (Objects.nonNull(teamMainPojoArray) && teamMainPojoArray.size() > BasicConstant.ZERO) {
            List<ReturnUserAndDepartmentPojo> ownerIds = teamMainPojoArray.toJavaList(ReturnUserAndDepartmentPojo.class);
            validateDataDTO.setOwnerIds(ownerIds);
        }
        if (Objects.nonNull(teamCoPojoArray) && teamCoPojoArray.size() > BasicConstant.ZERO) {
            List<ReturnUserAndDepartmentPojo> coUserIds = teamCoPojoArray.toJavaList(ReturnUserAndDepartmentPojo.class);
            validateDataDTO.setCoUserId(coUserIds);
        }
        try{
            teamUserHelp.beforeVerifyUserTeam(validateDataDTO);
        }catch (XbbException e){
            throw new XbbException(e.getCode(), teamUserHelp.formatErrorMessage(e.getCode(), e.getMsg(), XbbRefTypeEnum.PAY_PLAN));
        }
        TeamAfterVerifyDTO teamAfterVerifyDTO = validateDataDTO.getSaasNeedRedundantAttrPoJo().getTeamAfterVerifyDTO();
        addMuchFieldPojo.setTeamAfterVerifyDTO(teamAfterVerifyDTO);
    }

    /**
     * 以下计算方式需要改为付款单重新计算一遍，先展缓
     * @param corpid
     * @param purchaseId
     * @param idIn
     * @param isTotalPaymentSheet
     * @param formDataUpdateGetDTO
     * @return
     * @throws XbbException
     */
    public Double beforeSaveGetTotalAmount(String corpid, Long purchaseId, List<Long> idIn, Boolean isTotalPaymentSheet,FormDataUpdateGetDTO formDataUpdateGetDTO) throws XbbException {
        Double payPlanAmount = 0D;
        List<AggSumDTO> sumList = new ArrayList<>();
        AggSumDTO aggSumDTO = new AggSumDTO();
        aggSumDTO.setAttr(PayPlanEnum.AMOUNT.getAttr());
        aggSumDTO.setField(PayPlanEnum.getAttrConnectData(PayPlanEnum.AMOUNT));
        sumList.add(aggSumDTO);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(PayPlanEnum.getEsAttr4Keyword(PayPlanEnum.LINK_PURCHASE), purchaseId));
        if ( !idIn.isEmpty() ) {
            boolQueryBuilder.filter(boolQuery().mustNot(termsQuery(BasicConstant.DATAID, idIn)));
        }
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAY_PLAN;

        List<AggSumVO> aggSumList = esHelper.aggSumByField(indexTypeEnum.getIndex(), indexTypeEnum.getType(), sumList, searchQuery);
        for ( AggSumVO aggSumVO : aggSumList ) {
            if ( PayPlanEnum.AMOUNT.getAttr().equals(aggSumVO.getAttr()) ) {
                Double amount = aggSumVO.getValue() == null ? 0D : Double.parseDouble(aggSumVO.getValue().toString());
                payPlanAmount = Arith.add(payPlanAmount, amount);
            }
        }
        if ( Objects.nonNull(isTotalPaymentSheet) && isTotalPaymentSheet ) {
            formDataUpdateGetDTO.setDataId(purchaseId);
            payPlanAmount = fundMoneyHelp.getCheckAmount(formDataUpdateGetDTO,XbbRefTypeEnum.PURCHASE.getCode(),payPlanAmount);
        }
        return payPlanAmount;
    }
}
